package dumpserver

import (
	"fmt"
	"github.com/nick/vdamtools/apps/config"
	"net"
	"os"
)

type DumpServer struct {
	host string
	port int
}

func AddDumpServer() *DumpServer {
	return &DumpServer{}
}

func (c *DumpServer) Run() {
	startServer("0.0.0.0", int(config.GlobalConfig.Server.Port))

}

func startServer(host string, port int) {
	// 创建监听地址
	address := fmt.Sprintf("%s:%d", host, port)

	// 监听指定的地址和端口
	listener, err := net.Listen("tcp", address)
	if err != nil {
		fmt.Println("Error starting server:", err)
		os.Exit(1)
	}
	defer listener.Close()

	fmt.Printf("Server listening on %s\n", address)

	for {
		// 接受一个新的连接
		conn, err := listener.Accept()
		if err != nil {
			fmt.Println("Error accepting connection:", err)
			continue
		}
		fmt.Printf("Connection from %s\n", conn.RemoteAddr())

		go handleConnection(conn)
	}
}

func handleConnection(conn net.Conn) {
	defer conn.Close()

	buf := make([]byte, 1024)
	for {
		// 接收数据
		n, err := conn.Read(buf)
		if err != nil {
			if err != os.ErrClosed {
				fmt.Println("Error reading data:", err)
			}
			break
		}
		if n == 0 {
			break
		}

		// 将数据转换为HEX字符串
		receivedHex := fmt.Sprintf("%X", buf[:n])
		fmt.Printf("Received: %s\n", receivedHex)

		// 发送相同的数据回客户端
		_, err = conn.Write(buf[:n])
		if err != nil {
			fmt.Println("Error sending data:", err)
			break
		}

		// 打印发送的HEX字符串
		fmt.Printf("Sent: %s\n", receivedHex)
	}
	fmt.Printf("Connection closed from %s\n", conn.RemoteAddr())
}
